package com.chinafree.business.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinafree.auth.model.bo.TokenMap;
import com.chinafree.auth.service.TokenService;
import com.chinafree.business.mapping.UserMapping;
import com.chinafree.business.model.param.CompanyParam;
import com.chinafree.business.model.queryCondition.BaseQueryCondition;
import com.chinafree.business.model.result.CompanyResult;
import com.chinafree.business.service.CompanyService;
import com.chinafree.business.service.UserService;
import com.chinafree.mapper.MaCompanyMapper;
import com.chinafree.model.po.MaCompany;
import com.chinafree.model.po.MaUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CompanyServiceImpl extends BaseServiceImpl implements CompanyService {

    @Autowired
    private MaCompanyMapper maCompanyMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @Override
    public CompanyResult getCompanyInfo(Long companyId) {
        if (companyId == null) {
            companyId = getCompanyId();
        }
        MaCompany maCompany = maCompanyMapper.selectById(companyId);
        return getCompanyResult(maCompany);
    }

    CompanyResult getCompanyResult(MaCompany maCompany) {
        CompanyResult companyResult = UserMapping.instance.maCompanyToResult(maCompany);
        companyResult.setCityName(userService.getCityNameById(companyResult.getCityId()));
        return companyResult;
    }

    @Override
    public void update(CompanyParam body) {
        MaCompany maCompany = UserMapping.instance.companyParamToMaCompany(body);
        maCompany.setId(getCompanyId());
        maCompanyMapper.updateById(maCompany);
    }

    @Override
    public String insert(CompanyParam body) {
        MaCompany maCompany = UserMapping.instance.companyParamToMaCompany(body);
        maCompanyMapper.insert(maCompany);
        MaUser maUser = new MaUser();
        maUser.setId(getUserId());
        maUser.setCompanyId(maCompany.getId());
        userService.update(maUser);
        String token = tokenService.getToken(TokenMap.builder().companyId(String.valueOf(maCompany.getId()))
                .userId(getUserId().toString()).roleId(getRoleId().toString()).build());
        return token;
    }

    @Override
    public List<CompanyResult> getCompany(BaseQueryCondition condition) {
        Page<MaCompany> page = new Page<>(condition.getPageIndex(), condition.getPageSize());

        Page<MaCompany> maJobPage = maCompanyMapper.selectPage(page, null);
        List<CompanyResult> collect = maJobPage.getRecords().stream().map(this::getCompanyResult)
                .collect(Collectors.toList());
        
        return collect;
    }

}
